<?php
/**
 * 导入模型
 */

namespace plugins\qbt_custom_model\service;

use think\Config;
use think\Db;

class ImportService
{
    //导入sql
    public static function import_sql($filename)
    {
        try {
            $sqls = file_get_contents($filename);
            //将sql文件中的sql语句分解为一个个数组成员，并运行
            $sqls = preg_replace("/\n/s", "", $sqls);
            $arr = explode(";", $sqls);
            $config = Config::get('database');
            foreach ($arr as $k => $v) {
                if ($v != "") {
                    if (strpos($v, 'CREATE') !== false) {
                        $table = getNeedBetween($v,'`','(');
                        $table = str_replace('`','',trim($table));
                        $table_name = Db::query("select count(*) from information_schema.TABLES t where t.TABLE_SCHEMA =\"{$config['database']}\" and t.TABLE_NAME =\"{$table}\"");
                       if($table_name[0]['count(*)']==0){
                           Db::query($v);
                       }
                        $table=null;
                        $table_name=null;
                    } else {
                        Db::query($v);
                    }
                }
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }

    }

    /**
     * 导入zip
     */
    public static function import_zip($filename)
    {
        $foldername = UPLOAD_LOCAL_ROOT . 'model/';
        $zip = new \ZipArchive;
        if ($zip->open($filename) !== TRUE) {
            return false;
        }
        $zip->extractTo($foldername);//提取全部文件
        $zip->close();
        //导入sql
        $res = static::import_sql($foldername . 'model.sql');
        if ($res == false) {
            return false;
        }
        //开始移动文件
        xCopy($foldername . 'controller', APP_PATH . 'admin/controller/', 0);
        xCopy($foldername . 'model', APP_PATH . 'admin/model/', 0);
        xCopy($foldername . 'validate', APP_PATH . 'admin/validate/', 0);

        $view_path = CMF_ROOT . "public/themes/admin_simpleboot3/admin/";
        xCopy($foldername . 'view', $view_path, 1);

        //复制图片
        xCopy($foldername . 'admin', UPLOAD_LOCAL_ROOT . 'admin/', 1);
        xCopy($foldername . 'portal', UPLOAD_LOCAL_ROOT . 'portal/', 1);
        return true;
    }


}